package com.example.demo1.config;

import com.example.demo1.Service.UserDetailsServiceImpl;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@Configuration
@Order(99)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/assets/**","/favicon.ico", "/error","/image/**","/icons/**","/nav_img/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .and()
                .authorizeRequests()
                // /error 异常端点不需要用户认证
                .antMatchers("/error/**","/admin/login/tofindpassword","/admin/login/findpassword","/admin/login").permitAll()
                // 其余的全部需要用户认证
                .antMatchers("/admin/**").access("hasAnyRole('ADMIN')")
                .and()
                .formLogin().loginPage("/admin/login").permitAll().defaultSuccessUrl("/select").and()
                .logout()
                .logoutUrl("/logout").permitAll().logoutSuccessUrl("/admin/login").and()
                .csrf()
                .disable();
    }
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
